import {
	getToken,
	setToken,
	removeToken,
	setHistory,
	getHistory,
	removeHistory
} from "@/utils/storageSync"
import {
	historyAdd,
	historyAddOne
} from "@/services/collectionHistory"
const history = getHistory() ? getHistory() : []
export default {
	namespaced: true,
	state: {
		token: getToken(),
		history: history,
		maxHistoryNum: 30 //历史记录显示最近多少条
	},
	getters: {
		token: state => {
			return state.token
		},
		history: state => {
			return state.history
		}
	},
	mutations: {
		setUserToken(state, token) {
			state.token = token
			setToken(token)
		},
		removeUserToken(state) {
			state.token = ""
			removeToken()
		},
		addHistoryMu(state, data) {
			if (!state.token) {
				let history = add(data,state.maxHistoryNum,state.history)
				 state.history = history
				setHistory(history)
			}else{
				let tmp = {}
				if(data.hasOwnProperty('store')){
					tmp.type = 'store'
					tmp.id = data.store
				}else if(data.hasOwnProperty('housing')){
					tmp.type = 'housing'
					tmp.id = data.housing
				}else if(data.hasOwnProperty('building')){
					tmp.type = 'building'
					tmp.id = data.building
				}	
				historyAddOne({'history':tmp}).then(res=>{
					if(res.code == 100){
						let history = add(data,state.maxHistoryNum,state.history)
						state.history = history
						setHistory(history)
						state.token = ""
						removeToken()
					}
				})
			}
		},
		historyAddUser(state) {      //登陆后调用
		let history = state.history
			if (state.token && history.length > 0) {
				historyAdd({
					history_array: history
				})
				state.history = []
				removeHistory()
			}
		},
		removeHistoryMu(state) {
			state.history = []
			removeHistory()
		},
	}
}

function add(data,maxHistoryNum,history){
	if (data.hasOwnProperty('store')) { //商铺历史记录
		history = forReturn(data,history,'store')
	} else if (data.hasOwnProperty('housing')) { //房屋历史记录
		history = forReturn(data,history,'housing')
	}else if(data.hasOwnProperty('building')){
		history = forReturn(data,history,'building')
	}
	let length = history.length
	if (length > maxHistoryNum) {
		for (let i =maxHistoryNum; i < length; i++) {
			history.splice(i, 1)
		}
	}
	return history
}

function forReturn(data,history,field){
	for (let i = 0; i < history.length; i++) {   //删除旧数据 添加新数据
		if (history[i].type == field && history[i].id == data[field]) {
			history.splice(i, 1)
			break;
		}
	}
	history.unshift({
		type: field,
		id: data[field]
	})
	return history
}